package com.bw.android.bwgao6week2a.vm;

import android.view.View;
import android.widget.Toast;

import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.bw.android.bwgao6week2a.AppInstance;
import com.bw.android.network.RequestClient;
import com.bw.android.network.bean.LiveListBean;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Author: conghao
 * Date: 2023/10/9 10:03
 * Description: WatchViewModel
 */
public class WatchViewModel extends ViewModel {
    private LiveListBean.ResultBean liveBean;
    /**
     * 关注状态
     * true：已关注; false：未关注
     */
    private boolean hasFollow = false;
    public MutableLiveData<String> followStr = new MutableLiveData<>("关注");

    public void setLiveBean(LiveListBean.ResultBean mLiveBean) {
        this.liveBean = mLiveBean;
    }

    public void onClickFollow(View view) {
        if (hasFollow) {
            RequestClient.buildService().cancelFollow(
                            AppInstance.getInstance().getUserId(),
                            AppInstance.getInstance().loginResultBean.getSessionId(),
                            String.valueOf(liveBean.getAnchorId())
                    ).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(statusBean -> {
                        hasFollow = false;
                        Toast.makeText(view.getContext(), statusBean.message, Toast.LENGTH_LONG).show();
                        updateText();
                    }, throwable -> {
                        System.out.println(throwable.toString());
                    });
        } else {
            RequestClient.buildService().doFollow(
                            AppInstance.getInstance().getUserId(),
                            AppInstance.getInstance().loginResultBean.getSessionId(),
                            String.valueOf(liveBean.getAnchorId())
                    ).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(statusBean -> {
                        hasFollow = true;
                        Toast.makeText(view.getContext(), statusBean.message, Toast.LENGTH_LONG).show();
                        updateText();
                    }, throwable -> {
                        System.out.println(throwable.toString());
                    });
        }
    }
    private void updateText() {
        if (hasFollow) {
            followStr.setValue("已关注");
        } else {
            followStr.setValue("关注");
        }
    }
}
